import Compressor from 'compressorjs'
import base64 from 'base64-js'

export default function compress (file: File, quality?: number) {
  return new Promise<string>(resolve => {
    if (!quality) {
      quality = 0.8
    }
    const _ = new Compressor(file, {
      quality: quality,
      maxWidth: 2000,
      maxHeight: 2000,
      mimeType: 'image/jpeg',
      beforeDraw (context: CanvasRenderingContext2D, canvas: HTMLCanvasElement) {
        context.fillStyle = '#fff'
        context.fillRect(0, 0, canvas.width, canvas.height)
      },
      success (res: Blob) {
        res.arrayBuffer().then(ab => {
          resolve(base64.fromByteArray(new Uint8Array(ab)))
        })
      }
    })
  })
}
